import { Context, Next } from "koa";
import { birthday } from "../config/web.config";
import { AddBrowse, SelectBrowseCount } from "../dao/browse-dao";
import { SelectAllContent, SelectTopContent } from "../dao/content-dao";
import {
  resultErrorJson,
  resultSuccessJson,
  resultType,
} from "../util/resultError";

/***
 * 登录主界面接口
 **/
export const LoginService = async (ctx: Context, next: Next) => {
  try {
    
    const liveDays = Math.ceil(
      (new Date().getTime() - birthday) / (24 * 60 * 60 * 1000)
    );

    await AddBrowse({ ip: ctx.request.ip });

    const browseCount = await SelectBrowseCount();
    
    const content = await SelectAllContent();
    const tops = await SelectTopContent({top:3});
    
    ctx.body = resultSuccessJson(undefined, "登录成功", {
      content,
      liveDays,
      tops,
      contentNum: content.length,
      browseCount:browseCount[0]["count(*)"]
    });
  } catch (error) {
    ctx.body = resultErrorJson(
      resultType.sqlError,
      `LoginService Sql Error`,
      { error }
    );
  }
  return next;
};
